<template>
  <div class="examination-order-form">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
    >
      <!-- 患者信息展示 -->
      <el-card shadow="never" class="patient-info-card">
        <template #header>
          <div class="card-header">
            <span>患者信息</span>
          </div>
        </template>
        <el-descriptions :column="3" border size="small">
          <el-descriptions-item label="姓名">{{
            patientInfo.name
          }}</el-descriptions-item>
          <el-descriptions-item label="年龄"
            >{{ patientInfo.age }}岁</el-descriptions-item
          >
          <el-descriptions-item label="性别">{{
            patientInfo.gender
          }}</el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 检查项目选择 -->
      <el-card shadow="never" class="exam-selection-card">
        <template #header>
          <div class="card-header">
            <span>检查项目选择</span>
            <div class="header-actions">
              <el-input
                v-model="searchKeyword"
                placeholder="搜索检查项目..."
                clearable
                style="width: 200px"
              >
                <template #prefix>
                  <el-icon><Search /></el-icon>
                </template>
              </el-input>
            </div>
          </div>
        </template>

        <!-- 检查项目分类 -->
        <div class="exam-categories">
          <el-radio-group
            v-model="activeCategory"
            @change="handleCategoryChange"
          >
            <el-radio-button label="all">全部</el-radio-button>
            <el-radio-button
              v-for="category in examCategories"
              :key="category.value"
              :label="category.value"
            >
              {{ category.label }}
            </el-radio-button>
          </el-radio-group>
        </div>

        <!-- 检查项目列表 -->
        <div class="exam-items-grid">
          <div
            v-for="item in filteredExamItems"
            :key="item.item_id"
            class="exam-item-card"
            :class="{
              selected: isItemSelected(item.item_id),
              inactive: !item.is_active,
            }"
            @click="toggleExamItem(item)"
          >
            <div class="exam-item-content">
              <div class="exam-name">{{ item.item_name }}</div>
              <div class="exam-department">{{ item.operation_department_name }}</div>
              <div class="exam-fee">¥{{ item.standard_price }}</div>
              <div class="exam-desc">{{ item.description }}</div>
              <div class="exam-meta">
                <span class="exam-unit">{{ item.unit }}</span>
                <span class="exam-time">预计: {{ item.estimatedTime }}</span>
              </div>
            </div>
            <div class="exam-selection-indicator">
              <el-icon v-if="isItemSelected(item.item_id)" class="selected-icon">
                <Check />
              </el-icon>
              <el-tag
                v-if="!item.is_active"
                size="small"
                type="info"
                class="inactive-tag"
              >
                停用
              </el-tag>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="filteredExamItems.length === 0" class="empty-state">
          <el-empty description="暂无检查项目" :image-size="100" />
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-state">
          <el-skeleton :rows="3" animated />
        </div>
      </el-card>

      <!-- 已选项目 -->
      <el-card
        shadow="never"
        class="selected-items-card"
        v-if="selectedExamItems.length > 0"
      >
        <template #header>
          <div class="card-header">
            <span>已选检查项目 ({{ selectedExamItems.length }})</span>
            <el-button type="danger" text @click="clearAllSelection">
              清空全部
            </el-button>
          </div>
        </template>

        <el-table :data="selectedExamItems" size="small">
          <el-table-column prop="item_name" label="检查项目" min-width="200" />
          <el-table-column prop="operation_department_name" label="科室" width="120" />
          <el-table-column prop="standard_price" label="费用" width="100">
            <template #default="{ row }"> ¥{{ row.standard_price }} </template>
          </el-table-column>
          <el-table-column prop="unit" label="单位" width="80" />
          <el-table-column label="操作" width="80">
            <template #default="{ row }">
              <el-button link type="danger" @click="removeExamItem(row.item_id)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 费用汇总 -->
        <div class="fee-summary">
          <div class="fee-total">
            <span class="fee-label">总费用:</span>
            <span class="fee-amount">¥{{ totalFee }}</span>
          </div>
          <div class="fee-remark">
            <el-text type="info" size="small">
              费用标准依据医院收费规定，最终以实际结算为准
            </el-text>
          </div>
        </div>
      </el-card>

      <!-- 备注信息 -->
      <el-card shadow="never" class="remarks-card">
        <template #header>
          <div class="card-header">
            <span>备注信息</span>
          </div>
        </template>

        <el-form-item label="临床诊断" prop="clinicalDiagnosis">
          <el-input
            v-model="formData.clinicalDiagnosis"
            placeholder="请输入临床诊断信息"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="检查要求" prop="examRequirements">
          <el-input
            v-model="formData.examRequirements"
            type="textarea"
            :rows="3"
            placeholder="请输入特殊检查要求或注意事项"
            maxlength="500"
            show-word-limit
          />
        </el-form-item>

        <!-- 医保信息提示 -->
        <div class="insurance-tip" v-if="hasInsuranceItems">
          <el-alert title="医保提示" type="info" :closable="false" show-icon>
            <template #default>
              <div>所选项目中包含医保报销项目，具体报销比例以医保政策为准</div>
            </template>
          </el-alert>
        </div>
      </el-card>
    </el-form>

    <!-- 底部操作 -->
    <div class="form-actions">
      <el-button @click="handleCancel">取消</el-button>
      <el-button
        type="primary"
        @click="handleExanOrderSubmit"
        :loading="submitting"
        :disabled="selectedExamItems.length === 0"
      >
        开具检查 ({{ selectedExamItems.length }}个项目)
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { Search, Check } from "@element-plus/icons-vue";
// 引入API接口
import { getCheckFeeItemList,createExamOrderByDoctor } from "@/api/doctor";

const props = defineProps({
  patientInfo: {
    type: Object,
    required: true,
  },
  diagnosisId: {
    type: [String, Number],
    default: null,
  },
  //诊断记录对象数据，包含提交检查项目所需的必要信息
  diagnosisRecord: {
    type: Object,
    default: () => ({}),
  },
});

const emit = defineEmits(["close", "saved"]);

// 表单引用
const formRef = ref();
const submitting = ref(false);
const loading = ref(false);

// 搜索和筛选
const searchKeyword = ref("");
const activeCategory = ref("all");

// 表单数据
const formData = reactive({
  clinicalDiagnosis: "",
  examRequirements: "",
});

// 检查项目数据（从费用配置表获取）
const examItems = ref([]);
const selectedExamItems = ref([]);

// 检查分类映射（用于开具检查时）
const examCategories = ref([
  { value: "lab", label: "检验检查" },
  { value: "imaging", label: "影像检查" },
  { value: "functional", label: "功能检查" },
  { value: "endoscopy", label: "内镜检查" },
]);

// 表单验证规则
const formRules = {
  clinicalDiagnosis: [
    { required: true, message: "请输入临床诊断", trigger: "blur" },
  ],
};

// 计算属性
const totalFee = computed(() => {
  return selectedExamItems.value.reduce(
    (total, item) => total + (item.standard_price || 0),
    0
  );
});

const filteredExamItems = computed(() => {
  let filtered = examItems.value;

  // 关键词搜索过滤 - 根据item_name
  if (searchKeyword.value) {
    const keyword = searchKeyword.value.toLowerCase();
    filtered = filtered.filter(item => 
      item.item_name?.toLowerCase().includes(keyword)
    );
  }

  // 分类筛选 - 直接使用 check_type 字段
  if (activeCategory.value !== 'all') {
    filtered = filtered.filter(item => item.check_type === activeCategory.value);
  }

  return filtered;
});

const hasInsuranceItems = computed(() => {
  return selectedExamItems.value.some(
    (item) => item.insuranceType && item.insuranceType !== "self"
  );
});

// 方法
const isItemSelected = (itemId) => {
  return selectedExamItems.value.some((item) => item.id === itemId);
};

const toggleExamItem = (item) => {
  if (!item.is_active) {
    ElMessage.warning("该检查项目已停用，无法选择");
    return;
  }

  const index = selectedExamItems.value.findIndex(
    (selected) => selected.item_id === item.item_id
  );

  if (index > -1) {
    selectedExamItems.value.splice(index, 1);
  } else {
    selectedExamItems.value.push({
      ...item,
      paymentStatus: "pending",
      orderStatus: "created",
      applyTime: new Date().toISOString(),
    });
  }
};

const removeExamItem = (itemId) => {
  const index = selectedExamItems.value.findIndex((item) => item.item_id === itemId);
  if (index > -1) {
    selectedExamItems.value.splice(index, 1);
  }
};

const clearAllSelection = () => {
  if (selectedExamItems.value.length === 0) return;

  ElMessageBox.confirm("确定要清空所有已选检查项目吗？", "清空确认", {
    confirmButtonText: "确定清空",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      selectedExamItems.value = [];
      ElMessage.success("已清空所有检查项目");
    })
    .catch(() => {
      // 用户取消
    });
};

const handleCategoryChange = () => {
  // 分类筛选逻辑已在计算属性中处理
};


// TODO: 加载检查项目数据（从费用配置表获取）
const loadExamItems = async () => {
  loading.value = true;
  try {
    const response = await getCheckFeeItemList();

    if(response && response.code == 200){
        examItems.value = response.data.map(item =>({
          ...item,
          estimatedTime:"30分钟",
          payment_status:"pending",
          order_status:"created",
        }));
        ElMessage.success("加载检查项目成功")
    }
  } catch (error) {
    console.error("加载检查项目失败:", error);
    ElMessage.error("加载检查项目失败");
  } finally {
    loading.value = false;
  }
};

// 完善提交检查项目订单数据构建
const buildExaminationOrderData = () => {
  const currentUser = JSON.parse(localStorage.getItem('user') || '{}');  

  return {
    visit_id: props.diagnosisRecord?.visit_id,
    order_no: '', // 生成订单号 -- 由后端生成
    patient_name: props.patientInfo.name,
    patient_age: props.patientInfo.age,
    patient_gender: props.patientInfo.gender,
    insurance_card_number: props.patientInfo.insurance_card_number, //已经修复
    id_number: props.diagnosisRecord.id_number,
    doctor_id: currentUser.user_id,
    doctor_name: currentUser.doctor_name,
    department_id: currentUser.department_id,
    department_name: currentUser.department_name,
    clinical_diagnosis: formData.clinicalDiagnosis,
    exam_requirements: formData.examRequirements,
    total_fee: totalFee.value,
    order_status: 'created',
    payment_status: 'pending',
    apply_time: new Date().toISOString(),
    order_items: selectedExamItems.value.map(item => ({
      fee_item_id: item.item_id,
      exam_name: item.item_name,
      department_id: item.operation_department_id, // 执行的科室ID
      department_name: item.operation_department_name, // 执行的科室名称
      unit_price: item.standard_price,
      quantity: 1,
      amount: item.standard_price,
      exam_category: mapFeeCategoryToExamCategory(item.category_id), // 分类映射
      unit: item.unit,
      estimated_time: item.estimatedTime,
      description: item.description,
      insurance_type: item.insurance_type || 'self',
      item_status: 'pending',
      result_status: 'pending'
    }))
  };
};

// 费用分类到检查分类的映射
const mapFeeCategoryToExamCategory = (categoryId) => {
  const categoryMap = {
    1: 'REG', // 挂号费
    2: 'EXAM',    // 检查费  
    3: 'TREAT', // 治疗费
    4: 'MED' , // 药品费
    5: 'MAT' , // 材料费
    6: 'SURG' , // 手术费
    7: 'INP' , // 住院费
  };
  return categoryMap[categoryId] || '';
};

// 用于提交的费用类型映射


/**
 * 提交检查项目订单
 * 已正确修复
 * */ 
const handleExanOrderSubmit = async () => {
  try {
    if (selectedExamItems.value.length === 0) {
      ElMessage.warning("请至少选择一个检查项目");
      return;
    }

    await formRef.value.validate();
    submitting.value = true;

    // 构建提交数据
    const orderData = buildExaminationOrderData();

    // console.log("提交检查项目订单数据请求:", orderData);

    // return;

    // TODO: 替换为真实接口调用
    const response = await createExamOrderByDoctor(orderData)

    if(!response || response.code !== 200){
      throw new Error(response.message || "开具检查失败");    }

    ElMessage.success(`成功开具 ${selectedExamItems.value.length} 个检查项目`);
    emit("saved", selectedExamItems.value);
  } catch (error) {
    if (error instanceof Error) {
      console.error("开具检查失败:", error);
      ElMessage.error("开具检查失败");
    }
  } finally {
    submitting.value = false;
  }
};

const handleCancel = () => {
  if (selectedExamItems.value.length > 0) {
    ElMessageBox.confirm(
      "确定要取消开具检查吗？已选择的项目将不会保存。",
      "取消确认",
      {
        confirmButtonText: "确定取消",
        cancelButtonText: "继续编辑",
        type: "warning",
      }
    )
      .then(() => {
        emit("close");
      })
      .catch(() => {
        // 用户取消
      });
  } else {
    emit("close");
  }
};

// 生命周期
onMounted(() => {
  loadExamItems();

  console.log("ExaminationOrderForm加载时");
  console.log(props.patientInfo)

  // 如果诊断记录中有临床诊断，自动填充
  if (props.diagnosisRecord) {
    // TODO: 加载诊断记录中的临床诊断
    formData.clinicalDiagnosis = props.diagnosisRecord.preliminary_diagnosis||"初步诊断"; // 初步诊断
  }
});
</script>

<style lang="scss" scoped>
.examination-order-form {
  max-height: 70vh;
  overflow-y: auto;
  padding-right: 8px;
}

.patient-info-card {
  margin-bottom: 16px;
}

.exam-selection-card {
  margin-bottom: 16px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;

    .header-actions {
      display: flex;
      align-items: center;
    }
  }
}

.exam-categories {
  margin-bottom: 16px;
  padding: 0 4px;
}

.exam-items-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 12px;
  margin-bottom: 16px;
}

.exam-item-card {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  background: white;

  &:hover {
    border-color: #409eff;
    box-shadow: 0 2px 8px rgba(64, 158, 255, 0.1);
  }

  &.selected {
    border-color: #409eff;
    background: #f0f7ff;

    .exam-selection-indicator {
      opacity: 1;
    }
  }

  &.inactive {
    background: #f5f7fa;
    border-color: #dcdfe6;
    cursor: not-allowed;

    .exam-item-content {
      opacity: 0.6;
    }

    &:hover {
      border-color: #dcdfe6;
      box-shadow: none;
    }
  }

  .exam-item-content {
    .exam-name {
      font-weight: 600;
      font-size: 14px;
      color: #303133;
      margin-bottom: 4px;
    }

    .exam-department {
      font-size: 12px;
      color: #909399;
      margin-bottom: 4px;
    }

    .exam-fee {
      font-size: 16px;
      font-weight: 600;
      color: #e6a23c;
      margin-bottom: 6px;
    }

    .exam-desc {
      font-size: 12px;
      color: #606266;
      line-height: 1.4;
      margin-bottom: 8px;
      min-height: 34px;
    }

    .exam-meta {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 11px;
      color: #909399;

      .exam-unit {
        background: #f0f2f5;
        padding: 2px 6px;
        border-radius: 3px;
      }
    }
  }

  .exam-selection-indicator {
    position: absolute;
    top: 8px;
    right: 8px;
    opacity: 0;
    transition: opacity 0.3s;
    display: flex;
    flex-direction: column;
    align-items: flex-end;
    gap: 4px;

    .selected-icon {
      color: #67c23a;
      font-size: 16px;
    }

    .inactive-tag {
      margin: 0;
    }
  }
}

.empty-state {
  padding: 40px 0;
  text-align: center;
}

.loading-state {
  padding: 20px 0;
}

.selected-items-card {
  margin-bottom: 16px;

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .fee-summary {
    margin-top: 16px;
    padding-top: 16px;
    border-top: 1px solid #ebeef5;

    .fee-total {
      text-align: right;
      margin-bottom: 8px;

      .fee-label {
        font-size: 14px;
        color: #606266;
        margin-right: 8px;
      }

      .fee-amount {
        font-size: 20px;
        font-weight: 600;
        color: #e6a23c;
      }
    }

    .fee-remark {
      text-align: right;
    }
  }
}

.remarks-card {
  margin-bottom: 16px;

  .insurance-tip {
    margin-top: 16px;
  }
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 0;
  border-top: 1px solid #ebeef5;
  margin-top: 20px;
}

// 响应式设计
@media (max-width: 768px) {
  .exam-items-grid {
    grid-template-columns: 1fr;
  }

  .exam-selection-card .card-header {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;

    .header-actions {
      justify-content: space-between;
    }
  }
}

// 滚动条样式
:global(::-webkit-scrollbar) {
  width: 6px;
}

:global(::-webkit-scrollbar-track) {
  background: #f1f1f1;
  border-radius: 3px;
}

:global(::-webkit-scrollbar-thumb) {
  background: #c0c4cc;
  border-radius: 3px;
}

:global(::-webkit-scrollbar-thumb:hover) {
  background: #909399;
}
</style>